#include<iostream>
#include "TCP_Server.h"
#include<unistd.h>
#include<cstdlib>
#include<cstdio>
#include<sys/errno.h>
#include<fcntl.h>
#include<string.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<string.h>
#include<arpa/inet.h>
#define SERVPORT 9877
//#define LISTENQ 4
using namespace std;

void str_echo(const int sockfd)
{
	ssize_t n;
	char buf[MAX];
	char filename[MAX];
	n = read(sockfd, buf, sizeof(buf)); //read the file name :D
	buf[n] = 0;
	strcpy(filename,buf);
	strcat(filename,".rir");
	pid_t pid;
	char *arg_list[] = {"Compressor",buf, filename,NULL};
	char *env_list[] = {"USER=unknown","PATH=/tmp:/usr/bin:.",NULL};
	pid=vfork();
	if(pid==0)//child process
	{
		printf("Before Execution of the huff by the Child..\n");
		if(execve("/home/samiriff/Project/DCP-v8.0/Server/huff",arg_list,env_list)==-1){perror("Exec:");exit(1);}
	}
	if(waitpid(pid,NULL,0)<0){perror("waitpid");exit(1);}

	int outputfile = open(filename,O_RDONLY);
	while((n = read(outputfile, buf, sizeof(buf)))>0)
		write(sockfd, buf, n);
	cout<<filename<<" Sent Successfully\n";
	exit(0);
}
int main(int argc, char **argv)
{
	int listenfd, connfd;
	pid_t childpid;
	socklen_t clilen;
	struct sockaddr_in cliaddr, servaddr;
	listenfd = socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(SERVPORT);
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);

	bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr));

	listen(listenfd, LISTENQ);

	while(1)
	{
		clilen = sizeof(cliaddr);
		connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen);
		if((childpid = fork()) == 0)
		{
			close(listenfd);
			str_echo(connfd);
			exit(0);
		}
		close(connfd);
	}
}
